# -*- coding: utf-8 -*-
import pandas as pd

from global_data.glabal_data import GlobalData
from utils.dialog_utils import DialogUtils
from utils.file_utils import FileUtils
from utils.str_utils import StrUtils
from utils.time_utils import TimeUtils


class ChartManage(object):

    @classmethod
    def load_files(cls):
        """
        选择加载文件，按顺序返回文件列表
        :return:
        """
        res, ext = DialogUtils.get_files(path=GlobalData.CHART_CSV_PATH, ext="csv文件 (*.csv);")
        if len(res) > 20:
            # DialogUtils.alert(f"选中的文件超过20个，请重新选择！！！")
            return f"选中的文件超过20个，请重新选择！！！", None, None, None
        if len(res) == 0:
            # DialogUtils.alert(f"请先选择文件！！！")
            return f"请先选择文件！！！", None, None, None
        chart_files_list = []
        for i in range(len(res)):
            file_name = FileUtils.get_filename(res[i], False)
            file_time = StrUtils.split_str(file_name, "-")[-1]
            chart_files_list.append({"name": file_name, "time": file_time, "path": res[i],
                                     "currtime": TimeUtils.get_datetime_from_string(file_time,
                                                                                    "%Y%m%d%H%M%S")})
        chart_files_list = sorted(chart_files_list, key=lambda item: item["time"])
        return "", chart_files_list, chart_files_list[0]["currtime"], chart_files_list[-1]["currtime"]

    @classmethod
    def load_layer(cls, path, curr_date):
        """
        获取排列表
        :param curr_date:
        :return:
        """
        csvtype = GlobalData.CHART_CSV_TYPE
        # path = GlobalData.CHART_CSV_PATH
        path = FileUtils.join_path(path, curr_date)

        if FileUtils.dir_exists(path):
            if csvtype == "1":
                dirs = FileUtils.listdir(path, "dir")
                return "", dirs
            else:
                files = FileUtils.listdir(path, "file")
                files = [file.replace(".csv", "") for file in files]
                return "", files
        else:
            return f"目录【{path}】不存在，请检查！", []

    @classmethod
    def get_files_by_times(cls, path, curr_date, layer, begin_time, end_time):
        """
        根据时间段获取文件
        :param begin_time:
        :param end_time:
        :return:
        """
        csvtype = GlobalData.CHART_CSV_TYPE
        # path = GlobalData.CHART_CSV_PATH
        if csvtype == "1":
            path = FileUtils.join_path(path, curr_date, layer)
            begin_time = begin_time + "00"
            end_time = end_time + "59"
            res_files = []
            if FileUtils.dir_exists(path):
                files = FileUtils.listdir(path, "file")
                files = sorted(files)
                for file in files:
                    if begin_time <= file <= end_time:
                        file_name = FileUtils.get_filename(file, False)
                        file_time = f"{curr_date}{file_name}"
                        res_files.append({"name": file_name, "time": file_time, "path": f"{path}/{file}",
                                          "currtime": TimeUtils.get_datetime_from_string(file_time,
                                                                                         "%Y%m%d%H%M%S")})
                return "", res_files
            else:
                return f"目录【{path}】不存在，请检查！", []
        else:
            path = FileUtils.join_path(path, curr_date, layer + ".csv")
            if FileUtils.file_exists(path):
                return "", [{"name": layer, "time": "", "path": path, "currtime": None}]
            else:
                return f"文件【{path}】不存在，请检查！", []

    @classmethod
    def load_data_by_file(cls, file_list, begin_time, end_time):
        csvtype = GlobalData.CHART_CSV_TYPE
        # path = GlobalData.CHART_CSV_PATH
        print(begin_time, end_time)
        point_data = []
        if csvtype == "1":
            for ele in file_list:
                data = pd.read_csv(ele["path"])
                point_data.append(data)
            return point_data
        else:
            # 全量载入，根据时间过滤    切分不同的块
            data = pd.read_csv(file_list[0]["path"], parse_dates=["时间"])
            # df = data.query(f"时间>={begin_time} and 时间<={end_time}")
            df = data[(data["时间"] >= begin_time) & (data["时间"] <= end_time)]
            groups = df.groupby(["分组"])
            for _, group in groups:
                point_data.append(group)
            return point_data


if __name__ == '__main__':
    print("Python")
